<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 通用工具栏组件使用 -->
      <page-tools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共{{ total }}条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button
            v-power="'import'"
            type="danger"
            size="small"
            @click="$router.push('/excel')"
          >导入excel</el-button>
          <el-button
            v-power="'export'"
            type="success"
            size="small"
            @click="exportExcelFn"
          >导出excel</el-button>
          <el-button
            type="primary"
            size="small"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px">
        <el-table border :data="employeesList">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template v-slot="scope">
              <image-holder :src="scope.row.staffPhoto" class="staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column
            label="工号"
            prop="workNumber"
            :sort-method="sortMethodFn"
            sortable
          />
          <el-table-column label="聘用形式">
            <template v-slot="scope">
              <span>{{ formatEmployeeFn(scope.row.formOfEmployment) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间">
            <template v-slot="scope">
              <span>{{ formatEmployessDateFn(scope.row.timeOfEntry) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail?id=${scope.row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small" @click="setEmp(scope.row.id)">分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="delEmp(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 15, 20, 25]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          /> </el-row></el-card>

      <!-- 新增员工的弹窗 -->
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        @close="closeDialogFn"
      >
        <emp-form
          ref="empForm"
          :tree-data="treeData"
          @addEmployeeEv="addEmployeeFn"
          @closeFn="showDialog = false"
        />
      </el-dialog>

      <!-- 角色分配弹窗 -->
      <el-dialog title="分配角色" :visible="showRoleDialog" @close="cancleDialog">
        <!-- 设置角色组件 -->
        <assign-role-dialog ref="assignRole" :user-id="employeeId" :role-list="roleList" @confirm="confirmFn" @close="showRoleDialog = false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getEmployeeListAPI,
  getDepartmentsListAPI,
  addEmployeeAPI,
  delEmployeeAPI,
  getRolesAPI,
  getUserDetailByIdAPI,
  assignRolesAPI
} from '@/api'
import { transTree, formatEmployessDate } from '@/utils'
import EmpForm from './component/empForm.vue'
import AssignRoleDialog from './component/assignRoleDialog.vue'
export default {
  name: 'Employees',
  components: {
    EmpForm,
    AssignRoleDialog
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10 // 每页条数
      },
      employeesList: [], // 员工列表
      total: 0, // 数据总条数
      showDialog: false, // 新增员工 - 控制弹窗
      showRoleDialog: false, // 分配角色 - 控制弹窗
      employeeId: '', // 分配角色的 id
      treeData: [], // 树状结构数据
      roleList: [] // 所有角色信息
    }
  },
  created() {
    // 获取员工 -> 铺设页面
    this.getEmployeeListFn()
    // 获取部门 -> 树状结构
    this.getEmployeeDepartmentFn()
    // 获取角色 -> 所有角色信息
    this.getRoleListFn()
  },
  methods: {
    // 获取部门 -> 树状结构
    async getEmployeeDepartmentFn() {
      const res = await getDepartmentsListAPI()
      this.treeData = transTree(res.data.depts, '')
    },
    // 获取员工 -> 铺设也面
    async getEmployeeListFn() {
      const res = await getEmployeeListAPI(this.query)
      this.employeesList = res.data.rows
      this.total = res.data.total
      console.log(res)
    },

    // 获取角色 -> 所有角色信息
    async getRoleListFn() {
      const res = await getRolesAPI()
      this.roleList = res.data.rows
      console.log(res)
    },

    formatEmployeeFn(str) {
      if (String(str) === '1' || str === '正式') return '正式'
      else return '非正式'
    },

    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployeeListFn()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeeListFn()
    },

    // 自定义排序规则
    sortMethodFn(a, b) {
      return a.workNumber - b.workNumber
    },

    // 新增员工的事件
    async addEmployeeFn(data) {
      const res = await addEmployeeAPI(data)
      this.$message.success(res.message)
      this.getEmployeeListFn()
    },

    // 弹窗关闭的事件
    closeDialogFn() {
      this.$refs.empForm.$refs.addForm.resetFields()
      this.showDialog = false
    },

    // 删除员工
    async delEmp(id) {
      // 显示删除询问对话框
      const delRes = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (delRes === 'cancel') return this.$message.info('您取消了删除')
      const res = await delEmployeeAPI(id)
      if (!res.success) return
      this.$message.success(res.message)

      // 记住页面还没有重新铺设 判断条件为 1
      if (this.employeesList.length === 1) {
        this.query.page--
        if (this.query.page === 0) {
          this.query.page = 1
        }
      }

      this.getEmployeeListFn()
    },
    // 导出Excel的方法
    exportExcelFn() {
      const arr = [
        {
          key: 'id',
          value: '序号'
        },
        {
          key: 'username',
          value: '姓名'
        },
        {
          key: 'staffPhoto',
          value: '头像'
        },
        {
          key: 'mobile',
          value: '手机号'
        },
        {
          key: 'workNumber',
          value: '工号'
        },
        {
          key: 'formOfEmployment',
          value: '聘用形式'
        },
        {
          key: 'departmentName',
          value: '部门'
        },
        {
          key: 'timeOfEntry',
          value: '入职时间'
        }
      ]
      const tHeader = arr.map((obj) => obj.value)
      // 同一个内存地址 影响原数组了
      // const data = this.employeesList.map((item, index) => arr.map((obj) => {
      //   if (item.id) {
      //     item.id = index
      //   }
      //   return item[obj.key]
      // }))
      const data = this.employeesList.map((item, index) => {
        const keyArr = arr.map((obj) => obj.key)
        const value = keyArr.map((key) => {
          if (key === 'id') {
            return index
          } else if (key === 'formOfEmployment') {
            if (String(item[key]) === '1' || item[key] === '正式') {
              return '正式'
            } else return '非正式'
          }
          return item[key]
        })
        return value
      })
      console.log(data)
      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '1.xlsx',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },

    // 格式化员工入职时间
    formatEmployessDateFn(timer) {
      return formatEmployessDate(timer)
    },

    // 分配角色弹窗关闭的事件
    cancleDialog() {
      this.showRoleDialog = false
      this.$refs.assignRole.roleIdArr = []
    },

    // 表格 - 角色分配按钮的事件
    async setEmp(id) {
      this.employeeId = id
      this.showRoleDialog = true
      // 先标签后结构
      const res = await getUserDetailByIdAPI(id)
      this.$refs.assignRole.roleIdArr = res.data.roleIds
    },

    // 分配角色点击确定 子组件传出来的
    async confirmFn(roleIds) {
      const res = await assignRolesAPI({
        id: this.employeeId,
        roleIds
      })
      if (res.success) this.$message.success(res.message)
      this.cancleDialog()
    }
  }
}
</script>

<style lang="scss" scoped>
.staffPhoto {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>
